import { defineStore } from 'pinia'
import { login as loginApi, logout as logoutApi } from '../api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.userInfo?.role === 'ROLE_ADMIN'
  },
  
  actions: {
    async login(loginData) {
      try {
        const { data } = await loginApi(loginData)
        this.token = data.token
        this.userInfo = data.userInfo
        
        localStorage.setItem('token', data.token)
        localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
        return data.userInfo.role // 返回用户角色，方便根据角色跳转
      } catch (error) {
        throw error
      }
    },
    
    async logout() {
      try {
        // 尝试调用登出API
        await logoutApi()
        return true
      } catch (error) {
        console.error('登出API调用失败:', error)
        // 即使API调用失败，也继续清除本地状态
      } finally {
        // 无论成功失败都清除本地状态
        this.token = ''
        this.userInfo = {}
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        return true // 总是返回成功
      }
    }
  }
}) 